﻿using PrinterMonitorSvc.Common;
using PrinterMonitorSvc.Core.Attribute;
using PrinterMonitorSvc.Ext;
using PrinterMonitorSvc.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PrinterMonitorSvc.Controller
{
    /// <summary>
    /// 配置
    /// </summary>
    [RequestMapping("config")]
    public class ConfigController : ControllerBase
    {
        public ConfigController(HttpListenerRequest request, HttpListenerResponse response) : base(request, response)
        {
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="request"></param>
        /// <param name="stream"></param>
        [PostMapping]
        public bool SaveConfig()
        {
            var config = QueryString["config"];
            if (string.IsNullOrWhiteSpace(config))
            {
                throw new Exception("The print configuration that needs to be saved cannot be empty");
            }
            else
            {
                //用来判断格式是否正确
                JsonHelper.ConvertObj<Dictionary<string, string>>(config);
                return FileHelper.SaveFile(config, "Config.txt".ToPhysicalPath());
            }
        }

        /// <summary>
        /// 获取配置数据
        /// </summary>
        /// <returns></returns>
        [GetMapping]
        public Dictionary<string, string> GetConfig()
        {
            return GetServiceConfig();
        }

        /// <summary>
        /// 获取业务配置数据
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> GetServiceConfig()
        {
            var config = JsonHelper.ConvertObj<Dictionary<string, string>>(FileHelper.ReadFile(SystemConstant.CONFIG_NAME.ToPhysicalPath(), false));
            return config;
        }
    }
}
